package com.ys.web.ws.send.schedule;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ys.base.BaseConstants;
import com.ys.base.EnumType;
import com.ys.utils.base.j2se.Convert;
import com.ys.utils.base.j2se.DateUtil;
import com.ys.utils.base.j2se.JsonUtil;
import com.ys.utils.help.GroupUtils;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.GroupKey;
import com.ys.utils.redis.key.UserKey;
import com.ys.web.user.friends.mapper.GroupInfoMapper;
import com.ys.web.user.friends.po.BaseGroupInfoPO;
import com.ys.web.ws.bean.MessageResponseBean;
import com.ys.web.ws.send.mapper.GChatMapper;
import com.ys.web.ws.send.mapper.GChatReadMapper;
import com.ys.web.ws.send.po.GChatReadPO;
import com.ys.web.ws.send.service.impl.MessageServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ 名称:消息定时清理
 * @ 创建人: dhf
 * @ 参数： null
 * @ 创建时间: 2022/5/11
 * @ 修改人和其它信息
 * @ 返回值:
 */
@Slf4j
public class MessageClearSchedule implements Job {

    @Autowired
    private GroupInfoMapper groupInfoMapper;

    /**
     * @ 名称:清除验证
     * @ 创建人: dhf
     * @ 参数： now
     * @ 参数： setTime
     * @ 参数： code
     * @ 创建时间: 2022/5/11
     * @ 修改人和其它信息
     * @ 返回值: boolean
     */
    private boolean clearValidate(long now, long setTime, Integer code) {
        long suffix = (now - setTime) % EnumType.MessageClearCode.getValueByCode(code);
        if (suffix >= 0 && suffix < 60) {
            return true;
        }
        return false;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //获取所有组
        Date date = new Date();
        long time = date.getTime();
        long now = time / 1000;
        List<BaseGroupInfoPO> list = groupInfoMapper.selectEffectiveGroupInfo();

        list.forEach(obj -> {
            //准备数据
            MessageResponseBean messageResponseBean = new MessageResponseBean();
            messageResponseBean.setCode(EnumType.MessageCode.MESSAGE_CLEAR.getCode());
            messageResponseBean.setCreateTime(DateUtil.getDate(date, BaseConstants.BASE_FORMAT));
            // 时间判断是否发送、判断是否需要发送
            if (this.clearValidate(now, obj.getClearSetTime(), obj.getClearSetCode())) {
                //避免线程资源共享
                messageResponseBean.setGroupId(String.valueOf(obj.getId()));
                messageResponseBean.setWindowId(BaseConstants.GROUP_PREFIX + obj.getId());
                Set<String> range = Redis.zSet.range(GroupKey.groupMembersKey(obj.getId()), 0, -1);

                ThreadUtil.execAsync(() -> range.forEach(o -> {
                    //通知类型消息处理
                    String key = UserKey.noticeKey(o);
                    if (Redis.key.exists(key)) {
                        List<String> messageJsonList = Redis.list.range(key, 0L, -1L);
                        //取到之后删除数据
                        Redis.key.del(key);

                        List<String> collect = messageJsonList.stream().map(x -> JsonUtil.jsonToBean(x, MessageResponseBean.class))
                                .filter(x -> x.getWindowId().startsWith(BaseConstants.SINGLE_PREFIX) ||
                                        (x.getWindowId().startsWith(BaseConstants.GROUP_PREFIX) && x.getGroupId().equals(String.valueOf(obj.getId())) && DateUtil.getDate(date, BaseConstants.BASE_FORMAT).compareTo(x.getCreateTime()) < 0))
                                .map(JsonUtil::toJson)
                                .collect(Collectors.toList());
                        if (!collect.isEmpty()) {
                            Redis.list.pushList(key, collect);
                        }
                    }
                    GroupUtils.sendIfAbsentForClear(messageResponseBean, o);

                }));
            }
        });
    }
}
